﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Willows.Model
{
	public partial class SignalOutConnector
		: SignalConnectorBase
	{
		public override void DatapathMovedDownInHierarchy(Module newParent, Module oldParent)
		{
				if (Output is Signal)
				{
					Signal signal = Output as Signal;

					// create a new out connector on the new parent module
					SignalOutConnector outConnector = 
						new SignalOutConnector(newParent, TypeRegistry, Type);
					newParent.Connectors.Add(outConnector.LocalName, outConnector);

					signal.UnbindInput(this);
					signal.BindInput(outConnector);

					outConnector.BindInput(this);
					outConnector.BindOutput(signal);

					UnbindOutput(signal);
					BindOutput(outConnector);
				}
				else
					throw new NotImplementedException();	
		}

		public override void DatapathMovedUpInHierarchy(Module newParent, Module oldParent)
		{

			if (Output is Signal)
			{
				Signal signal = Output as Signal;

				// Create a new in connector on the old parent module					
				SignalInConnector inConnector =
					new SignalInConnector(oldParent, TypeRegistry, Type);

				oldParent.Connectors.Add(inConnector.LocalName, inConnector);

				// Create a new signal in the new parent module to connect
				// this connector with the new in connector on the old parent
				Signal newSignal =
					new Signal(newParent, TypeRegistry, Type);

				newParent.Channels.Add(newSignal.LocalName, newSignal);

				UnbindOutput(signal);
				BindOutput(newSignal);

				newSignal.BindInput(this);
				newSignal.BindOutput(inConnector);

				inConnector.BindOutput(signal);
				inConnector.BindInput(newSignal);

				signal.UnbindInput(this);
				signal.BindInput(inConnector);
			}
			else
				throw new NotImplementedException();

		}

		public Module GetWritingDatapath()
		{
			return null;
		}

		private static int uniqueNameCnt = 0;
		private static string GetNextUniqueName()
		{
			return string.Format("signal_writer{0}", uniqueNameCnt++);
		}

		public SignalOutConnector(Module parent, TypeRegistry typeRegistry, Type type)
			: this(parent, typeRegistry, type, GetNextUniqueName())
		{
		}

		private SignalOutConnector(Module parent, TypeRegistry typeRegistry, Type type, string name)
			: base(parent, typeRegistry, type, name, name)
		{
			
		}

		public SignalOutConnector(Module parent, TypeRegistry typeRegistry, Type type, string name, string uniqueName)
			: base(parent, typeRegistry, type, name, uniqueName)
		{
		}
	}
}
